import axios from 'axios';
// import qs from 'qs';
// import api from "./api.js"
// axios.defaults.withCredentials = true; //让ajax携带cookie
axios.defaults.timeout = 5000;
axios.defaults.baseURL = 'https://api.kags.com';

//http request 请求拦截器
axios.interceptors.request.use(config => {
	config.data = JSON.stringify(config.data);
	config.headers = {
		'Content-Type': 'application/x-www-form-urlencoded'
	};
	return config;
});


//http response 返回拦截器
axios.interceptors.response.use(response => {
	// 这里可以判断404啥的
	// return Promise.reject('你大爷你大爷你大爷你大爷');
	return response;
}, error => {
	// 接口请求失败统一处理
	if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
		console.log('你大爷的请求超时')
	}
	return Promise.reject(error);
});

// 调用时使用async、await，可以在try、catch中统一

export function get(url, data = {}) {
	console.log(url, data);
	return new Promise((resolve, reject) => {
		axios.get(url, {
			params: data
		}).then(response => {
			resolve(response.data);
		}).catch(err => {
			console.log(err, '接口有问题，index.js');
			// reject(err);
		})
	});
}

export function post(url, data = {}) {
	return new Promise((resolve, reject) => {
		axios.post(url, data)
			.then(response => {
				resolve(response.data);
			}, err => {
				reject(err);
			});
	});
}

export function patch(url, data = {}) {
	return new Promise((resolve, reject) => {
		axios.patch(url, data)
			.then(response => {
				resolve(response.data);
			}, err => {
				reject(err);
			});
	});
}

export function put(url, data = {}) {
	return new Promise((resolve, reject) => {
		axios.put(url, data)
			.then(response => {
				resolve(response.data);
			}, err => {
				reject(err);
			});
	});
}